<form class="layui-form seller-form" action="">

    <div class="layui-form-item">

        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">年度：</label>
            <div class="layui-input-inline" id="year_box">
                <select name="year" lay-filter="year" id="year" list="year_list" lay-search>
                    <option value=""></option>
                    <datalist  id="year_list" lay-search>
                        {volist name="yearList" id="yearList"}
                        <option value="{$yearList.id}">{$yearList.year}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">季度：</label>
            <div class="layui-input-inline" id="season_box">
                <select name="season" lay-filter="season" id="season" list="season_list" lay-search>
                    <option value=""></option>
                    <datalist  id="season_list" lay-search>
                        {volist name="seasonList" id="seasonList"}
                        <option value="{$seasonList.season_id}">{$seasonList.season_name}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">类型：</label>
            <div class="layui-input-inline">
                <select id="type_id" lay-filter="type_id" name="type_id">
                    <option value=''>请选择</option>
                    {volist name="typeList" id="vo"}
                    <option value="{$vo.id}">{$vo.name}</option>
                    {/volist}
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">参数：</label>
            <div class="layui-input-inline" id="specialty_box">
                <select name="param_id" lay-filter="param_id" id="param_id" lay-search>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="search"><i class="iconfont icon-chaxun"></i>查询</button>
            <button type="button" id="add_rel" class="layui-btn layui-btn-sm add_rel"><i class="layui-icon">&#xe608;</i>添加</button>
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="import-bookRel"><i
                class="iconfont icon-cloudupload" style="font-size: 20px !important;" disabled></i>导入</button>
            <button id="exportBtn" class="layui-btn layui-btn-sm layui-btn-disabled" lay-submit lay-filter="export-bookRel"><i
                class="iconfont icon-clouddownload" style="font-size: 20px !important;" disabled></i>导出</button>
        </div>

    </div>

</form>

<div class="table-body">
    <table id="bookRelTable" lay-filter="bookRelTable"></table>
</div>

<div id="exportbookRel" style="display: none;">
    <form class="layui-form export-form" action="">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先筛选要导出的学生，默认导出全部
                </blockquote>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">任务名称：</label>
                <input type="text" name="taskname" lay-verify="title" style="width:200px;" placeholder="请输入任务名称"
                    autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>

<script>
    layui.use(['table', 'form', 'layer', 'laydate'], function () {
        var layer = layui.layer, table = layui.table, form = layui.form, date = layui.laydate;
        
        // 定义变量保存当前页面和当前页面数据条数
        var currPage; 
        var dataNum;

        //执行渲染
        table.render({
            elem: '#bookRelTable', //指定原始表格元素选择器（推荐id选择器）
            height: 'full-120',
            cellMinWidth: '80',
            page: 'true',
            limit: '20',
            id: 'bookRelTable',
            url: "{:url('BookCommon/returnNull')}",
            // url: "{:url('BookDraw/bookRelindex')}",
            cols: [[ //标题栏
                { type: 'numbers' },
                { field: 'plan_year', sort: true, title: '年度', width: 80, align: 'center' },
                { field: 'plan_season', sort: true, title: '季度', width: 80, align: 'center' },
                { field: 'type_name', title: '类型', width:80, align:'center'}, 
                { field: 'param_name', title: '参数', width:80, align:'center'}, 
                { field: 'book_name', title: '教材名称', width:200, align:'center'},
                { field: 'price', title: '教材单价', width:100, align:'center'},
                { field: 'book_disc', title: '折扣价', width:100, align:'center'},
                { field: 'book_num', title: '教材数量', width:100, align:'center'},
                { field: 'book_author', title: '主编', width:160, align:'center'},
                { field: 'book_concern', title: '出版社', width:180, align:'center'},
                { field: 'book_edition', title: '版次', width:160, align:'center'},
                { field: 'book_isbn', title: 'ISBN', width:160, align:'center'},
                { field: 'book_reward', title: '获奖情况', width:200, align:'center'},
                { field: 'book_date', title: '出版年限', width:120, align:'center'},
                { field: 'operating', title: '操作', width:120, align: 'center', templet:function(data){
                    var html = '';
                    html += '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>';
                    html += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';
                    return html;
                }},
            ]], //设置表头
            done: function(res, curr, count){
                // 判断加载结果数量是否大于0
                if(count>0){
                    $("#exportBtn").removeClass("layui-btn-disabled");
                    $('#exportBtn').removeAttr("disabled");
                } else {
                    $('#exportBtn').addClass("layui-btn-disabled");
                    $('#exportBtn').attr("disabled", true);
                }
                // 给变量赋值 
                dataNum = res.data.length;
                currPage = curr;
            },
            where: {"year": $("#year").val(), "season": $("#season").val()}
            //,…… //更多参数参考右侧目录：基本参数选项
        });

        // 查询
        form.on('submit(search)', function (data) {
            table.reload('bookRelTable', {
                where: data.field,
                page: {curr: 1},
                url: "{:url('BookDraw/BookExtraDrawBookRel')}",
            });
            return false;
        });

        // 导入
        layui.form.on('submit(import-bookRel)', function (data) {
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage('{:url("BookDraw/importBookRel")}', '导入非计划发放教材关联信息'); 
            return false;
        }); 

 
        // 监听工具条
        table.on('tool(bookRelTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if(layEvent === 'del'){ // 删除
                layer.confirm('真的要删除么',{icon: 3}, function(index){
                    JsPost("{:url('BookDraw/BookExtraDrawBookRelDel')}",{id:data.id}, function (res) {
                        //删除逻辑中判断只有一条数据时应该刷新前一页信息
                        layer.msg(res.msg);
                        if(res.status){
                            if(dataNum == 1){
                                currPage = currPage - 1;
                            }

                            table.reload('bookRelTable', {
                                page: {
                                    curr: currPage
                                }
                            });
                            return false;
                        }
                    });
                });
            } else if(layEvent === 'edit'){ // 编辑
                var editUrl = "{:url('BookDraw/BookExtraDrawBookRelEdit')}?id=" + data.id;
                var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
                topLayui.index.openTabsPage(editUrl, '编辑关联');
                return false;
            }
        });

        //非计划发放教材关联信息导出
        layui.form.on('submit(export-bookRel)', function (data) {
            layer.open({
                type: 1,
                title: '非计划发放教材关联数据导出',
                area: ['400px', '248px'], //宽高
                btn: ['确定', '取消'],
                content: $("#exportbookRel").html(),
                success: function () {
                    $(':focus').blur();
                    this.enterEsc = function(event){
                        if(event.keyCode === 13){
                            if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                                $(".layui-layer-btn0").addClass("layui-btn-disabled");

                                //判断是否有选中
                                var filter = $(".seller-form").serialize();
                                $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                                var data = $(".export-form:last").serializeArray();
                                data.push({ 'name': 'model', 'value': 'BookExtraDrawBookRel' });

                                if($.trim(data[0]['value']) == '') {
                                    layer.msg('请填写任务名称！', { time: 1300 });
                                    $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                    return false;
                                }

                                JsPost("{:url('Ietask/export')}", data, function (res) {
                                        layer.msg(res.msg, { time: 1500 }, function () {
                                            if (res.status) {
                                                layer.closeAll();
                                                //执行跳转
                                                var topLayui = parent === self ? layui : top.layui;
                                                topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                            } else {
                                                $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                            }
                                        });
                                    }
                                );
                            }
                            return false; //阻止系统默认回车事件
                        }
                    };
                    $(document).on('keydown', this.enterEsc);	//监听键盘事件，关闭层
                },
                yes: function () {
                    if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                        $(".layui-layer-btn0").addClass("layui-btn-disabled");

                        //判断是否有选中
                        var filter = $(".seller-form").serialize();
                        $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                        var data = $(".export-form:last").serializeArray();
                        if($.trim(data[0]['value']) == '') {
                            layer.msg('请填写任务名称！', { time: 1300 });
                            $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                            return false;
                        }

                        data.push({ 'name': 'model', 'value': 'BookExtraDrawBookRel' });
                        JsPost("{:url('Ietask/export')}", data, function (res) {
                                layer.msg(res.msg, { time: 1500 }, function () {
                                    if (res.status) {
                                        layer.closeAll();
                                        //执行跳转
                                        var topLayui = parent === self ? layui : top.layui;
                                        topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                    } else {
                                        $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                    }
                                });
                            }
                        );
                    }
                }, btn2: function () {
                    layer.closeAll();
                }, end: function(){
                    $(document).off('keydown', this.enterEsc);	        //解除键盘关闭事件
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        layui.use('form', function () {
            // 联动参数
            form.on('select(type_id)', function (data) {
                getParams(data);
            });
        });

        // 得到参数
        function getParams(data) {
            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getParams')}",
                data: 'type_id=' + data.value,
                success: function(e) {
                    if(e.status) {
                        $("#param_id").empty();//清空下拉框的值
                        $('#param_id').append(new Option('', ''));// 下拉菜单里添加元素 
                        $.each(e.data, function (index, item) {
                            $('#param_id').append(new Option(item.name, item.id));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 增加关联
        $(document).on('click', '.add_rel', function(){
            var url = "{:url('manage/BookDraw/BookExtraDrawBookRelAdd')}";
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage(url, '增加关联'); 
            return false;
        });
    })
 
    $("#year").val({$year});  // 年度：
    $("#season").val({$season});  // 季度： 
</script>